package org.flint92.springcloud.hystrix.future;

import java.util.Random;
import java.util.concurrent.*;

/**
 * @author flint92
 */
public class FutureCircuitBreakerDemo {

    public static void main(String[] args) {

        final ExecutorService service = Executors.newSingleThreadExecutor();

        RandomCommand command = new RandomCommand();

        Future<String> future = service.submit(command::run);

        String result;
        try {
            result = future.get(100, TimeUnit.MILLISECONDS);
        } catch (InterruptedException | TimeoutException | ExecutionException e) {
            result = command.getFallback();
        }

        System.out.println("Result is: " + result);

        service.shutdown();
    }


    static class RandomCommand implements Command<String> {

        private final Random r = new Random();

        @Override
        public String run() throws InterruptedException {

            long executeTime = r.nextInt(200);
            System.err.println("Execute Time is " + executeTime + " ms.");

            TimeUnit.MILLISECONDS.sleep(executeTime);

            return "Hello World!";
        }

        @Override
        public String getFallback() {
            return "Fallback.";
        }
    }

    public interface Command<T> {

        /**
         * 正常执行并且返回结果
         *
         * @return 结果
         */
        T run() throws Exception;

        /**
         * 错误时 返回容错结果
         *
         * @return 结果
         */
        T getFallback();

    }

}
